# coding=utf-8
"""
作者：董新强 
创建时间：2020-7-13
描述：错题管理
"""
from db_models.cat_answers import CatAnswers
from db_models.cat_questions import CatQuestions
from db_models.cat_test import CatTest
from framework.db_session import DbSession
from framework.log_util import trycatch
from framework.msg import failure, ok
from services.service_base import ServiceBase


class ErrorManage(ServiceBase):
    def __init__(self, usr):
        super().__init__(usr)

    @trycatch(failure(msg='获取错题失败'))
    def get_error_ls(self, aid):
        if not aid:
            return failure(msg='尚未进行测试')

        ls = []
        with DbSession.create() as db:
            test = db.query(CatTest.id).filter(CatTest.aid == aid).filter(CatTest.uid == self.uid).first()
            if not test:
                return failure(msg='尚未进行测试')

            query = db.query(CatQuestions.title, CatQuestions.options, CatQuestions.type, CatQuestions.answer) \
                .filter(CatQuestions.id == CatAnswers.qid) \
                .filter(CatAnswers.test_id == test[0]) \
                .filter(CatAnswers.answer == False) \
                .order_by(CatQuestions.id)
            for title, options, tp, answer in query:
                ls.append({
                    'title': title,
                    'options': options,
                    'type': tp,
                    'answer': answer
                })
        return ok(data=ls)


if __name__ == '__main__':
    inst = ErrorManage({'id': 1070})
    print(inst.get_error_ls(2).responseMsg())
